﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Xml.Linq;
//
using PerceptiveMCAPI.Types.Internal;
//
namespace PerceptiveMCAPI.Types
{
	public class ecommOrdersOutput : Api_BaseOutput
	{
		public ecommOrdersResults result { get; set; }
		public ecommOrdersParms inputParms { get; private set; }
		//
		public ecommOrdersOutput( ecommOrdersInput input )
			: base( input )
		{
			inputParms = input.parms;
			result = new ecommOrdersResults();
		}
		// --------------------------------------------------- tostring
		public override string ToString()
		{
			return "ToString() not yet implemented";
		}

		#region ================================================================== format setup
		// ---- serial
		internal void Format( string api_Request, string api_Response )
		{
			this.api_Request = api_Request;
			this.api_Response = api_Response;
			// ----------------------------------
			if ( this.api_OutputType == EnumValues.OutputType.JSON )
				outputJSON();
			else if ( this.api_OutputType == EnumValues.OutputType.XML )
				outputXML();
		}
		// ---- xmlrpc
		internal void Format( x_ecommOrders rpcResult )
		{
			this.api_Request = EnumValues.NotSupplied;
			this.api_Response = EnumValues.NotSupplied;
			// ------------------------
			this.result = FormatResults( rpcResult );
		}
		#endregion

		#region  ===================================================================== format result
		// ---------------------------------------------------------- outputXML
		protected void outputXML()
		{
			XElement xml = XElement.Parse( this.api_Response );
			// error check
			Api_Error error = apiSerial.GetXmlOutputError( xml );
			if ( error != null )
			{
				this.api_ErrorMessages.Add( error );
				return;
			}
			// -------------------------------------------- get values
			int it; double dbl; DateTime dt;
			try
			{
				int.TryParse( xml.Element( "total" ).Value, out it );
				result.total = it;
				//
				IEnumerable<XElement> data = xml.Element( "data" ).Elements( "struct" );
				foreach ( var xord in data )
				{
					ecommOrder ord = new ecommOrder();
					ord.store_id = xord.Element( "store_id" ).Value ?? "";
					ord.store_name = xord.Element( "store_name" ).Value ?? "";
					ord.order_id = xord.Element( "order_id" ).Value ?? "";
					ord.campaign_id = xord.Element( "campaign_id" ).Value ?? "";
					ord.email = xord.Element( "email" ).Value ?? "";
					double.TryParse( xord.Element( "order_total" ).Value, out dbl );
					ord.total = dbl;
					double.TryParse( xord.Element( "tax_total" ).Value, out dbl );
					ord.tax = dbl;
					double.TryParse( xord.Element( "ship_total" ).Value, out dbl );
					ord.shipping = dbl;
					DateTime.TryParse( xord.Element( "order_date" ).Value, out dt );
					ord.order_date = dt;
					// ---------
					if ( xord.Element( "lines" ).HasElements )
					{
						IEnumerable<XElement> lines = xord.Element( "lines" ).Elements( "struct" );
						foreach ( XElement line in lines )
						{
							var item = new ecommOrder.orderItem();
							int.TryParse( line.Element( "line_num" ).Value, out it );
							item.line_num = it;
							int.TryParse( line.Element( "product_id" ).Value, out it );
							item.product_id = it;
							item.product_name = line.Element( "product_name" ).Value ?? "";
							item.product_sku = line.Element( "product_sku" ).Value ?? "";
							int.TryParse( line.Element( "product_category_id" ).Value, out it );
							item.category_id = it;
							item.category_name = line.Element( "product_category_name" ).Value ?? "";
							int.TryParse( line.Element( "qty" ).Value, out it );
							item.qty = it;
							double.TryParse( line.Element( "cost" ).Value, out dbl );
							item.cost = dbl;
							//
							ord.items.Add( item );
						}
					}
					result.data.Add( ord );
				}
				//
			}
			catch ( Exception ex )
			{
				this.api_ErrorMessages.Add( apiException.FormatError( ex ) );
			}
		}
		// ---------------------------------------------------------- outputJSON
		protected void outputJSON()
		{
			JavaScriptSerializer jss = new JavaScriptSerializer();

			try
			{
				if ( this.api_Response.Contains( EnumValues.JSONErrorString ) )
				{
					Api_Error err = jss.Deserialize<Api_Error>( this.api_Response );
					this.api_ErrorMessages.Add( err );
				}
				else
				{
					x_ecommOrders jsonResult = jss.Deserialize<x_ecommOrders>( this.api_Response );
					this.result = FormatResults( jsonResult );
				}
			}
			catch ( Exception ex )
			{
				this.api_ErrorMessages.Add( apiException.FormatError( ex ) );
			}
		}
		// -----------------------------------------------------
		protected ecommOrdersResults FormatResults( x_ecommOrders x_results )
		{
			DateTime dt;
			var results = new ecommOrdersResults();
			//
			results.total = x_results.total;
			foreach ( var xord in x_results.data )
			{
				ecommOrder ord = new ecommOrder();
				ord.store_id = xord.store_id;
				ord.store_name = xord.store_name;
				ord.order_id = xord.order_id;
				ord.email = xord.email;
				ord.total = xord.order_total;
				ord.tax = xord.tax_total;
				ord.shipping = xord.ship_total;
				ord.order_date = DateTime.TryParse( xord.order_date, out dt ) ? dt : dt;
				// -- lines
				foreach ( var line in xord.lines )
				{
					var item = new ecommOrder.orderItem();
					//
					item.line_num = line.line_num;
					item.product_id = line.product_id;
					item.product_name = line.product_name;
					item.product_sku = line.product_sku;
					item.category_id = line.product_category_id;
					item.category_name = line.product_category_name;
					item.qty = line.qty;
					item.cost = line.cost;
					//
					ord.items.Add( item );
				}
				//------------------------
				results.data.Add( ord );
			}
			//------------------- 
			return results;
		}
		//
		#endregion
	}
}
